"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.adminMiddleware = exports.adminUpdate = void 0;
const Administrator_1 = require("../../lib/Administrator");
const socket_message_1 = require("../../utils/socket_message");
const utils_1 = require("../../utils/utils");
const log4js_1 = require("log4js");
const Member_1 = require("../../lib/Member");
const logger = (0, log4js_1.getLogger)('socket/adminUpdate');
async function adminUpdate(owner) {
    var _a;
    const administratorClassroom = (_a = Administrator_1.broadcastClassroom.get(Administrator_1.ADMINISTRATOR)) !== null && _a !== void 0 ? _a : new Set();
    return owner.axios.getAccount().then(({ code, data } = {}) => {
        if (+code === 0 && Array.isArray(data)) {
            for (const member of data) {
                if (member.typeCode === 'ddt') {
                    administratorClassroom.add(member.communicationAccount);
                }
                Member_1.allMemberCache.set(member.communicationAccount, member);
                if (member.communicationAccount === owner.userId) {
                    if (member.typeCode === 'ddt') {
                        owner.setLevel((0, utils_1.getLevel)(member.levelCode) + utils_1.ADMIN_LEVEL);
                    }
                    else {
                        owner.setLevel((0, utils_1.getLevel)(member.levelCode));
                    }
                }
            }
            Administrator_1.broadcastClassroom.set(Administrator_1.ADMINISTRATOR, administratorClassroom);
        }
        logger.debug(`adminUpdate:(${owner.username})`);
        return administratorClassroom;
    });
}
exports.adminUpdate = adminUpdate;
async function adminMiddleware(app, io) {
    const { socket } = app.locals;
    const { userId, username, userType } = socket.handshake.query;
    const administratorClassroom = Administrator_1.broadcastClassroom.get(Administrator_1.ADMINISTRATOR);
    if (administratorClassroom && administratorClassroom.has(userId)) {
        socket.join(Administrator_1.ADMINISTRATOR);
    }
    socket.on('administrator:refresh', async function (cb) {
        const owner = Member_1.Members.get(userId);
        const data = await adminUpdate(owner);
        cb && cb((0, socket_message_1.okMsg)('administrator:refresh', { members: [...data] }));
    });
}
exports.adminMiddleware = adminMiddleware;
